package com.five.calendar.function.home;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.five.calendar.ApplicationHelper;
import com.five.calendar.R;
import com.five.calendar.base.BaseFragment;
import com.five.calendar.common.observer.Observer;
import com.five.calendar.database.bean.ScheduleBean;
import com.five.calendar.database.bean.TargetBean;
import com.five.calendar.database.observer.ScheduleObservable;
import com.five.calendar.database.observer.TargetObservable;
import com.five.calendar.ui.activity.GoalDoneShowActivity;
import com.five.calendar.ui.activity.MainActivity;
import com.five.calendar.ui.calendarview.Utils;
import com.five.calendar.ui.calendarview.component.CalendarAttr;
import com.five.calendar.ui.calendarview.component.CalendarViewAdapter;
import com.five.calendar.ui.calendarview.interf.OnSelectDateListener;
import com.five.calendar.ui.calendarview.model.CalendarDate;
import com.five.calendar.ui.calendarview.view.Calendar;
import com.five.calendar.ui.calendarview.view.MonthPager;
import com.five.calendar.ui.calendarview.view.CustomDayView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @desc:
 * @auther:duwei
 * @date:2017/8/30
 */

public class HomeFragment extends BaseFragment {

    @BindView(R.id.calendar_home_monthpager)
    MonthPager mMonthPager;
    @BindView(R.id.calendar_home_recyclerview)
    RecyclerView mRecyclerView;
    private Context mContext;
    private OnSelectDateListener mOnSelectDateListener;
    private CalendarViewAdapter mCalendarAdapter;
    private ScheduleRecyclerAdapter mRecyclerViewAdapter;
    private CalendarDate mCurrentDate;
    private int mCurrentPage = MonthPager.CURRENT_DAY_INDEX;
    private ArrayList<Calendar> mCurrentCalendars = new ArrayList<>();
    private boolean initiated = false;
    private List<ScheduleBean> mList;
    private List<TargetBean> mTargetList;
    private Date todayEndDate;
    private Date todayEnd2Data;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = ApplicationHelper.getContext();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.calendar_home, container,false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mMonthPager.setViewheight(Utils.dpi2px(mContext, 270));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mCurrentDate = new CalendarDate();
        initCurrentDate();
        initCalendarView();
    }

    @Override
    public void onResume() {
        super.onResume();
        GoalDoneShowActivity.sTextColor = 0;
        initCurrentDate();
    }

    public void setCalendarDate(int year, int month){
        CalendarDate calendarDate = new CalendarDate(year, month, 1);
        CalendarDate calendarDate1 = new CalendarDate();
        if(calendarDate.getYear() == calendarDate1.getYear() && calendarDate.getMonth() == calendarDate1.getMonth()){
            calendarDate = calendarDate1;
        }
        if (mCalendarAdapter != null){
            mCalendarAdapter.notifyDataChanged(calendarDate);
        }
        mCurrentDate = calendarDate;
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.setCalendarTitle(calendarDate.getYear() + "-" + calendarDate.getMonth());
        refreshScheduleView(mCurrentDate);
    }

    private void refreshScheduleView(final CalendarDate calendarDate){
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int year = calendarDate.getYear();
        int month = calendarDate.getMonth();
        int day = calendarDate.getDay();
        String today = year + "-" + month + "-" + day + " 00:00:00";
        String todayEnd = year + "-" + month + "-" + day + " 23:59:59";
        String todayEnd2 = year + "-" + month + "-" + day + " 23:59:00";
        Date todayDate = null;
        try {
            todayDate = format.parse(today);
            todayEndDate = format.parse(todayEnd);
            todayEnd2Data = format.parse(todayEnd2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(todayDate != null && todayEndDate != null){
            ScheduleObservable.queryScheduleByTime(todayDate.getTime(), todayEndDate.getTime()).registerObserver(new Observer<ScheduleBean, Integer, List<ScheduleBean>>() {
                @Override
                public void onFail(Integer integer) {

                }

                @Override
                public void onComplete(List<ScheduleBean> scheduleBeans) {
                    if(scheduleBeans != null){
                       mList = scheduleBeans;
                    } else {
                       mList = new ArrayList<ScheduleBean>();
                    }
                    TargetObservable.queryTargetByTime(todayEnd2Data.getTime()).registerObserver(new Observer<TargetBean, Integer, List<TargetBean>>() {
                        @Override
                        public void onFail(Integer integer) {

                        }

                        @Override
                        public void onComplete(List<TargetBean> targetBeen) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                            Log.e("ZXX", sdf.format(todayEnd2Data));
                            if (targetBeen != null){
                                mTargetList = targetBeen;
                                Log.e("ZXX","targetSize: " + mTargetList.size());
                            } else {
                                mTargetList = new ArrayList<TargetBean>();
                            }
                            ScheduleRecyclerAdapter scheduleRecyclerAdapter = new ScheduleRecyclerAdapter(getActivity(), mList,mTargetList,calendarDate);
                            mRecyclerView.setAdapter(scheduleRecyclerAdapter);
                        }

                        @Override
                        public void onSuccess(TargetBean targetBean) {

                        }
                    }).startDataHandle();
                }

                @Override
                public void onSuccess(ScheduleBean scheduleBean) {

                }
            }).startDataHandle();
        }
    }
    public void initCalendarView() {
        initListener();
        CustomDayView customDayView = new CustomDayView(mContext, R.layout.calendar_home_custom_day);
        mCalendarAdapter = new CalendarViewAdapter(mContext, mOnSelectDateListener,
                CalendarAttr.CalendayType.MONTH, customDayView);
        initMarkData();
        initMonthPager();
    }

    private void initMarkData() {
        HashMap<String, String> markData = new HashMap<>();
        markData.put("2017-8-9", "1");
        markData.put("2017-7-9", "0");
        markData.put("2017-6-9", "1");
        markData.put("2017-6-10", "0");
        mCalendarAdapter.setMarkData(markData);
    }

    private void initCurrentDate() {
        refreshScheduleView(mCurrentDate);
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.setCalendarTitle(mCurrentDate.getYear() + "-" + mCurrentDate.getMonth());
    }

    private void initListener() {
        mOnSelectDateListener = new OnSelectDateListener() {
            @Override
            public void onSelectDate(CalendarDate date) {
                refreshClickDate(date);
            }

            @Override
            public void onSelectOtherMonth(int offset) {
                //偏移量 -1表示刷新成上一个月数据 ， 1表示刷新成下一个月数据
                mMonthPager.selectOtherMonth(offset);
            }
        };
    }

    private void refreshClickDate(CalendarDate date) {
        mCurrentDate = date;
        refreshScheduleView(mCurrentDate);
    }

    /**
     * 初始化monthPager，MonthPager继承自ViewPager
     *
     * @return void
     */
    private void initMonthPager() {
        mMonthPager.setAdapter(mCalendarAdapter);
        mMonthPager.setCurrentItem(MonthPager.CURRENT_DAY_INDEX);
        mMonthPager.setPageTransformer(false, new ViewPager.PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                position = (float) Math.sqrt(1 - Math.abs(position));
                page.setAlpha(position);
            }
        });
        mMonthPager.addOnPageChangeListener(new MonthPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mCurrentPage = position;
                mCurrentCalendars = mCalendarAdapter.getPagers();
                if (mCurrentCalendars.get(position % mCurrentCalendars.size()) instanceof Calendar) {
                    CalendarDate date = mCurrentCalendars.get(position % mCurrentCalendars.size()).getSeedDate();
                    mCurrentDate = date;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus && !initiated) {
            refreshMonthPager();
            initiated = true;
        }
    }

    private void refreshMonthPager() {
        CalendarDate today = new CalendarDate();
        mCalendarAdapter.notifyDataChanged(today);
    }
}
